import { Op } from "sequelize"
import { FilmMultimediaRelation } from "../entities/filmMultimediaRelation"
import { PLATFORM_TYPE } from "../constant/platform"
import { PlatformNotSupportError, PushlishJobAbortedError } from "../libs/errors"

export class FilmMultimediaRelationJob {
  constructor(opt) {
    this.queue = opt.queue
    this.filmReleaseService = opt.filmReleaseService
    this.platformDouyinPublishJob = opt.platformDouyinPublishJob
  }

  async execute(){
    const where = {
      release_status: FilmMultimediaRelation.RELEASE_STATUS_WAIT,
      job_time: {
        [Op.not]: null,
        [Op.lte]: new Date()
      }
    }

    FilmMultimediaRelation.chunk({
      where,
      order: [['id', 'ASC']],
      limit: 20
    }, async (rows) => {
      console.log(`本次发布视频数量为: ${rows.length}`)

      const controller = new AbortController();

      for (const row of rows) {
        console.log(`任务发布开始: ${row.id}`)

        // 标记为正在执行
        await this.filmReleaseService.updateFilmMultimediaRelationStatus(row.id, {
          release_status: FilmMultimediaRelation.RELEASE_STATUS_JOB
        })

        this.queue.add(async ({ signal }) => {
          try {
            signal.addEventListener('abort', async () => {          
              throw new PushlishJobAbortedError('Job aborted')
            });

            switch (row.platform) {
              case PLATFORM_TYPE.DOUYIN:
                await this.platformDouyinPublishJob.execute(row)
                break;
              case PLATFORM_TYPE.WECHAT:
                await this.platformDouyinPublishJob.execute(row)
                break;
              default:
                throw new PlatformNotSupportError('platform not support')
            }
          } catch (error) {
            if (error instanceof PushlishJobAbortedError) {
              await this.filmReleaseService.updateFilmMultimediaRelationStatus(row.id, {
                release_status: FilmMultimediaRelation.RELEASE_STATUS_FAIL,
                release_reason: error.message,
                api_failed: error.message,
              })
            }

            console.log('任务执行出错', error)
          }

          console.log(`任务发布完成: ${row.id}`)
        }, { signal: controller.signal });

        console.log(`任务投递完成: ${row.id}`)
      }
    })
  }
}